package org.example;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class test11 {
    public static void main(String[] args) throws Exception {

        String url = "https://test.home.tabledi.com/api/overview";

        try {
            String property = System.getProperty("user.home");
            File folder = new File(property, "/my_java_test");
            folder.mkdir(); //如果存在就不会继续创建
            File file = new File(folder, "/test1.txt");
//            file.createNewFile();

            //用于创建一个OkHttpClient对象来进行请求的配置和管理，可以用来发送一条或多条HTTP请求
            OkHttpClient client = new OkHttpClient();
            //通过Request.Builder可以设置请求的各种属性，如URL、请求头、请求体等。
            Request request = new Request.Builder()
                    //在这里使用.url(url)方法设置了请求的URL
                    .url(url)
                    //构建了最终的Request对象
                    .method("get", null)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();

                    if (responseBody != null) {
                        byte[] data = responseBody.bytes();
                        Files.write(Paths.get(file.getAbsolutePath()), data);

                    } else {
                        throw new Exception("啥也没有");
                    }
                } else {
                    throw new Exception("出错了");
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        URL url = new URL("https://test.home.tabledi.com/api/overview");
//
//        final String property = System.getProperty("user.home");
//
//        final File folder = new File(property, "/my_java_test");
//        System.out.println(folder);
//
//        folder.mkdir();
//        final File file = new File(folder, "/test1.txt");
//        file.createNewFile();
//
//        try (
//                InputStream is = url.openStream();
//                InputStream bis = new BufferedInputStream(is);
//                OutputStream os = new FileOutputStream(file);
//                OutputStream bos = new BufferedOutputStream(os);
//
//        ) {
//            byte[] buffer = new byte[1024];
//            int len;
//            while ((len = bis.read(buffer)) != -1) {
////
//                bos.write(buffer, 0, len);
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        //用okhttpclient
        //read和write封装成工具类
        //1.通过参数控制是否需要缓冲；2.设计工具类的签名及资源释放问题

    }

}

